package org.neowei.image.filtering.handle;

import java.awt.image.BufferedImage;

import org.neowei.image.api.ImageOption;

public class CropHandle implements IHandle {
	
	@Override
	public BufferedImage getBufferedImage(ImageOption imageOption, BufferedImage srcimage) {
		int cropX = imageOption.getCropX();
		int cropY = imageOption.getCropY();
		int srcwidth = imageOption.getSrcwidth();
		int srcheight = imageOption.getSrcheight();
		if (cropX < srcwidth && cropY < srcheight) {
			int neowidth = (imageOption.getNeowidth() == 0) ? srcwidth : imageOption.getNeowidth();
			int neoheight = (imageOption.getNeoheight() == 0) ? srcheight : imageOption.getNeoheight();
			boolean bwidth = neowidth + cropX > srcwidth;
			boolean bheight = neoheight + cropY > srcheight;
			if (bwidth && bheight) {
				return srcimage.getSubimage(cropX, cropY, srcwidth - cropX, srcheight - cropY);
			} else if (bwidth) {
				return srcimage.getSubimage(cropX, cropY, srcwidth - cropX, neoheight);
			} else if (bheight) {
				return srcimage.getSubimage(cropX, cropY, neowidth, srcheight - cropY);
			} else {
				return srcimage.getSubimage(cropX, cropY, neowidth, neoheight);
			}
		} else {
			return srcimage;
		}
	}
}
